import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useTagsStore } from './tags'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const token = ref(localStorage.getItem('token') || '')
  const menuList = ref(JSON.parse(localStorage.getItem('menuList') || '[]'))
  const routesAdded = ref(false)
  const setToken = (tokens: string) => {
    localStorage.setItem('token', tokens)
    token.value = tokens
  }
  const setUserInfo = (userInfo: any) => {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    userInfo.value = userInfo
  }
  const setMenuList = (newMenuList: any) => {
    localStorage.setItem('menuList', JSON.stringify(newMenuList))
    menuList.value = newMenuList
  }
  const setRoutesAdded = (bol: boolean) => {
    routesAdded.value = bol
  }
  const logout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('menuList')
    userInfo.value = {}
    token.value = ''
    menuList.value = []
    // 重置路由添加状态，确保下次登录能重新获取菜单
    setRoutesAdded(false)
    useTagsStore().clearTags()
  }
  return {
    userInfo,
    token,
    setToken,
    setUserInfo,
    menuList,
    setMenuList,
    logout,
    routesAdded,
    setRoutesAdded,
  }
})
